package com.example.demo.exception;

import com.example.demo.core.ResultDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.List;
import java.util.Set;

/**
 * @author ghl
 * @version 1.0
 * @date 2022/9/21 12:14
 * @description 全局异常处理
 */
@RestControllerAdvice
public class BaseExceptionHandle {

    private static final Logger logger = LoggerFactory.getLogger(BaseExceptionHandle.class);


    /**
     * 统一处理请求参数校验(实体对象传参)
     *
     * @param e BindException
     * @return FebsResponse
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultDTO handleBindException(BindException e) {
        StringBuilder message = new StringBuilder();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError error : fieldErrors) {
            message.append(error.getField()).append(error.getDefaultMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        logger.error(message.toString());
        ResultDTO<String> resultDTO = new ResultDTO<String>();
        resultDTO.setSuccess(false);
        resultDTO.setMessage(e.getMessage());
        return resultDTO;
    }

    /**
     * 统一处理请求参数校验(普通传参)
     *
     * @param e ConstraintViolationException
     * @return FebsResponse
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultDTO handleConstraintViolationException(ConstraintViolationException e) {
        StringBuilder message = new StringBuilder();
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for (ConstraintViolation<?> violation : violations) {
            Path path = violation.getPropertyPath();
            String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), ".");
            message.append(pathArr[1]).append(violation.getMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        logger.error(message.toString());

        ResultDTO<String> resultDTO = new ResultDTO<String>();
        resultDTO.setSuccess(false);
        resultDTO.setMessage(message.toString());
        return resultDTO;
    }

    /**
     * 统一处理请求参数校验(json)
     *
     * @param e MethodArgumentNotValidException
     * @return FebsResponse
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultDTO handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.error(e.getMessage(), e);
        StringBuilder message = new StringBuilder();
        for (FieldError error : e.getBindingResult().getFieldErrors()) {
            String defaultMessage = error.getDefaultMessage();
            if (!message.toString().contains(defaultMessage)) {
                message.append(error.getDefaultMessage()).append("!");
            }
        }
        logger.error(message.toString());
        ResultDTO<String> resultDTO = new ResultDTO<String>();
        resultDTO.setSuccess(false);
        resultDTO.setMessage(message.toString());
        return resultDTO;
    }

    @ExceptionHandler(value = HttpMediaTypeNotSupportedException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultDTO handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
        String message = "该方法不支持" + StringUtils.substringBetween(e.getMessage(), "'", "'") + "媒体类型";
        logger.error(message);

        ResultDTO<String> resultDTO = new ResultDTO<String>();
        resultDTO.setSuccess(false);
        resultDTO.setMessage(message.toString());
        return resultDTO;
    }

    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultDTO handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        String message = "该方法不支持" + StringUtils.substringBetween(e.getMessage(), "'", "'") + "请求方法";
        logger.error(message);
        ResultDTO<String> resultDTO = new ResultDTO<String>();
        resultDTO.setSuccess(false);
        resultDTO.setMessage(message.toString());
        return resultDTO;
    }


}
